package com.ruoyi.framework.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器
 * 记录访问的接口和接口耗时
 */
@Component
public class LogResponseTimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        long startTime = System.currentTimeMillis();

        // 在请求开始时将开始时间保存到请求属性中
        request.setAttribute("startTime", startTime);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        long endTime = System.currentTimeMillis();
        long startTime = (Long) request.getAttribute("startTime");
        long duration = endTime - startTime;

        // 打印请求的响应时间
        String requestURI = request.getRequestURI();
        // 打印请求的路径和方法
        String requestMethod = request.getMethod();

        System.err.println("request Method:【 " + requestMethod + " 】 request Path:【 " + requestURI + " 】 request Time:【 "+ duration + "ms 】");
        // 如果需要，还可以在这里处理异常（如果有的话）
    }
}